package org.lewis.demo.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.lewis.demo.util.ApiUtil;
import org.lewis.demo.util.RsaUtil;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("demo")
@RestController
public class DemoController {

    private final RsaUtil rsaUtil;
    private final ApiUtil apiUtil;

    public DemoController(RsaUtil rsaUtil, ApiUtil apiUtil) {
        this.rsaUtil = rsaUtil;
        this.apiUtil = apiUtil;
    }

    @GetMapping("keys")
    public ObjectNode keys() {
        try {
            KeyPair keyPair = this.rsaUtil.genKeyPair();

            ObjectNode node = new ObjectMapper().createObjectNode();
            node.put("privateKey", new String(Base64Utils.encode(keyPair.getPrivate().getEncoded())))
                    .put("publicKey", new String(Base64Utils.encode(keyPair.getPublic().getEncoded())));
            return node;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("keys/log")
    public void log() {
        try {
            this.rsaUtil.logKeyPair();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("post")
    public JsonNode post() {
        try {
            String url = "xxxxxxx";

            Map<String, Object> param = new HashMap<>();
            param.put("key1", "value1");
            param.put("key2", "value2");
            param.put("key3", "value3");

            return this.apiUtil.post(url, param);
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

}
